;;; cl-synth : A software synthesiser for Common Lisp
;;; Copyright (C) 2010  Richard van Roy - (pluijzer [at] gmail [dot] com)

;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation, either version 3 of the License, or
;;; (at your option) any later version.

;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.

;;; You should have received a copy of the GNU General Public License
;;; along with this program.  If not, see <http://www.gnu.org/licenses/>

(in-package :cl-synth)

(defun wait-beat (bpm)
  (let ((now  (get-internal-real-time))
	(msec (* (/ 60 bpm) 1000)))
    (loop while (not (>= (get-internal-real-time) (+ now msec))))))

(defun subfill (start length list)
  (subseq (extend list (+ start length) 0)
	  start (+ start length)))

(defun addat (a at b)
  (let ((c (extend b (+ at (length a)) 0)))
    (append (subseq c 0 at)
	    (operate-wave #'+ (subseq c at (+ (length a) at)) a)
	    (subseq c (+ (length a) at)))))

(defun compile-score-aux (score res)
  (if (not score) res
      (compile-score-aux (rest score)
			 (addat (first  (first score))
				(second (first score))
				res))))

(defmacro compile-score (score) 
  `(let ((sc (leval ,score)))
     (compile-score-aux sc nil)))

(defun beat (waves duration times)
  (let* ((beat-dur (/ duration (length waves)))
	 (once
	    (mapcan (lambda (x) (subfill 0 beat-dur x)) waves))
	 (total nil))
    (dotimes (i times)
      (setf total (append total once)))
    total))
  
  